from flask import request, Blueprint, render_template

from zz import zz_code, zz_redis, zz_dingtalk, zz_return

app = Blueprint('route_sys', __name__)


# 通用接口
@app.route('/test', methods=['GET'])
def test():
    r = zz_return.of(0)
    r.set_data("time", zz_code.date_tostring())
    r.set_data("server", zz_code.env("SERVER"))
    return r.to_json()


@app.route('/token', methods=['GET'])
def token():
    root = f"{request.scheme}://{request.host}"

    redis = zz_redis.of()
    run = redis.set_if_exists("console_run", "1", 3 * 60)  # 3分钟内，重复请求，不生成新token
    if run is False:
        return zz_return.of(20025, "3分钟内，重复请求，不生成新token").to_json()

    redis.delete_by_prefix("console:")
    token = zz_code.get_uuid()
    redis.get_client().setex(f"console:{token}", 3600, zz_code.date_tostring())
    server = zz_code.env("SERVER", "dev")

    url = f"{root}/console.html?token={token}"
    send_msg = f"**[{server}]**\n\n {zz_code.date_tostring()} \n\n**控制台授权** \n\n [授权链接]({url}) \n\n {token} \n\n"
    r = zz_dingtalk.send_markdown(send_msg, "控制台")
    if r.ok():
        r.set_errmsg("发送成功")
    return r.to_json()
